package com.tzl.design_pattern.factory_pattern.simple_factory_pattern;

/**
 * @author Zhilei Tang
 * @date Created in 2020/11/14 15:57
 */
public class SimpleFactory {
  /**
   * 这种方式的缺点： 每当需要新增一个产品实例时，都需要修改这个方法，违背了开闭原则
   *
   * @param product
   * @return
   */
  public static IProduct createProduct(String product) {
    switch (product) {
      case "apple":
        return new Apple();
      case "orange":
        return new Orange();
      default:
        throw new RuntimeException("暂时还没有这种产品哦。。。。");
    }
  }

  /**
   * 改进型
   *
   * @param clazz
   * @return
   * @throws IllegalAccessException
   * @throws InstantiationException
   */
  public static IProduct createProduct2(Class<? extends IProduct> clazz)
      throws IllegalAccessException, InstantiationException {
    if (clazz == null) {
      throw new RuntimeException("无法识别的产品类型");
    }
    return clazz.newInstance();
  }
}
